package com.example.taximeter.controller;

import com.example.taximeter.bean.*;
import com.example.taximeter.config.GlobalParam;
import com.example.taximeter.service.PrivilegeService;
import com.example.taximeter.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 用户管理
 */
@RestController
@RequestMapping(value = "/user", method = RequestMethod.POST)
public class UserController {

    private UserService userService;
    private PrivilegeService privilegeService;
//    private final static Logger logger = LoggerFactory.getLogger(ParamFileController.class);


    @Autowired
    public UserController(UserService userService,PrivilegeService privilegeService){
        this.userService = userService;
        this.privilegeService = privilegeService;
    }

    //查看用户列表
    @RequestMapping(value = "/all")
    public ReturnInfo findUserAll(@RequestParam(value = "pageNum", defaultValue = "0") String pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "0") String pageSize,
                                       @RequestBody UserView userView) {
        //添加日志
        userService.addUserLog(7,userView.toString());
        return userService.findUserAll(Integer.valueOf(pageNum), Integer.valueOf(pageSize), userView);
    }


//登录
    @RequestMapping(value = "/login")
    public ReturnInfo login(@RequestBody User user) {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPasswd());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);
            SecurityUtils.getSubject().getSession().setTimeout(-1000);
//            logger.info("登录"+user.toString());
            //添加日志
            userService.addUserLog(1,user.toString());
            return ReturnInfo.info5("登录成功", subject.getSession().getId().toString());
        } catch (Exception e) {
            if (e instanceof UnknownAccountException) {
                return ReturnInfo.info1("账户密码错误");
            }
            if (e instanceof LockedAccountException) {
                return ReturnInfo.info1("该账户不允许登录");
            }
            if(e instanceof AuthenticationException){
                return ReturnInfo.info1("账户密码错误");
            }
            return ReturnInfo.info1("未知错误");
        }
}
    //退出
    @RequestMapping(value = "/loginout")
    public void logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }
    //查看个人信息
    @RequestMapping(value = "/userinfo")
    public User findUserInfo(){
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        return userService.findUserByUserid(user.getId());// 数据库字段名和bean里的不一样
    }

    //查看用户角色
    @RequestMapping(value = "/userinfopriv")
    public List<RolePrivilege> findUserInfoPrev(){
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        User user1 = userService.findUserByUserid(user.getId());
        return privilegeService.findPriviegeByRole(user1.getRoleid());
    }


    //查看用户角色
    @RequestMapping(value = "/userview")
    public UserView findUserView(){
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        return userService.findUserViewByUserid(user.getId());
    }

    //查看用户角色权限
    @RequestMapping(value = "/userprivall")
    public List<RolePrivilege> findUserPrevAll(@RequestBody Role role){
        return privilegeService.findPriviegeAllByRole(role.getRoleid());
    }

    //查看用户名list
    @RequestMapping(value = "/usernamelist")
    public List<User> findUsernameList(){
        return userService.findUsernameList();
    }

    //查看真实姓名list
    @RequestMapping(value = "/fullnamelist")
    public List<User> findFullnameList(){
        return userService.findFullnameList();
    }

    //新增用户
    @RequestMapping(value = "/add")
    public ReturnInfo addUser(@RequestBody User user){
        String mes = userService.addUser(user);
        if(mes.equals("成功")){
//            logger.info("新增用户"+user.toString());
            //添加日志
            userService.addUserLog(4,user.toString());
        }
        return ReturnInfo.info1(mes);
    }

    //修改用户
    @RequestMapping(value = "/update")
    public ReturnInfo updateUser(@RequestBody UserView userView){
        String mes = userService.updateUser(userView);
        if(mes.equals("成功")){
//            logger.info("修改用户"+userView.toString());
            //添加日志
            userService.addUserLog(5,userView.toString());
        }
        return ReturnInfo.info1(mes);
    }
//
//    //查询用户（用户id）
//    @RequestMapping(value = "staffs/{zyid}", method = RequestMethod.GET)
//    public Staff findStaffByZyid(@PathVariable String zyid){
//        return userService.findStaffByZyid(zyid);
//    }
//
//    //新增用户
//    @RequestMapping(value = "staffs", method = RequestMethod.POST)
//    public ReturnInfo createStaff(@RequestBody @Validated(GroupCreate.class) Staff staff, BindingResult result) throws NoSuchAlgorithmException {
//        if(result.hasErrors()){
//            return ReturnInfo.info3("失败", GlobalParam.toErrors(result));
//        }
//        staff.setZyid(GlobalParam.getUUID());
//        return ReturnInfo.info1(userService.createStaff(staff));
//    }
//
//    //重置用户密码
//    @RequestMapping(value = "staffs/{zyid}", method = RequestMethod.PUT)
//    public ReturnInfo updateStaffPsw(@PathVariable String zyid){
//        return ReturnInfo.info1(staffService.updateStaffPsw(zyid));
//    }
//
    //删除用户
    @RequestMapping(value = "delete/{id}")
    public ReturnInfo deleteStaff(@PathVariable Integer id){
        //添加日志
        userService.addUserLog(6,String.valueOf(id));
        return ReturnInfo.info1(userService.deleteUser(id));
    }
}
